<template>
  <!-- <bread-crumb></bread-crumb>
  <x-card
    :message="message_card"
    :width="98"
    :height="height"
    style="margin: 20px 20px"
  > -->
  <!-- 搜索以及操作 -->
  <!-- 自定义组件 -->
  <x-search>
    <!-- 搜索的一系列东西 -->
    <template #search>
      <p>
        <a-input
          v-model:value="student_name"
          placeholder="查询学生姓名"
          style="width: 120px"
        />
      </p>
      <p style="margin-left: 10px">
        <a-input
          v-model:value="student_id"
          placeholder="查询学生学号"
          style="width: 120px"
        />
      </p>
      <p style="margin-left: 10px">
        <a-select
          v-model:value="class_id"
          placeholder="查询班级"
          style="width: 120px"
        >
          <a-select-option
            v-for="(value, index) in all_classes"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </p>
      <p style="margin-left: 10px">
        <a-select
          v-model:value="program_id"
          placeholder="查询专业"
          style="width: 120px"
        >
          <a-select-option
            v-for="(value, index) in all_programs"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </p>
      <p style="margin-left: 10px">
        <a-select
          v-model:value="ed_sys"
          placeholder="查询学制"
          style="width: 120px"
        >
          <a-select-option value="1"> 1年 </a-select-option>
          <a-select-option value="2"> 2年 </a-select-option>
          <a-select-option value="4"> 4年 </a-select-option>
        </a-select>
      </p>
      <p style="margin-left: 10px">
        <!-- 学生的学习状态：0 在读；1 休学；2 退学 -->
        <a-select
          v-model:value="student_state"
          placeholder="查询状态"
          style="width: 120px"
        >
          <a-select-option value="0"> 在读 </a-select-option>
          <a-select-option value="1"> 休学 </a-select-option>
          <a-select-option value="2"> 退学 </a-select-option>
        </a-select>
      </p>
      <a-button type="primary" style="margin-left: 10px" @click="but_search"
        >搜索</a-button
      >
      <a-button style="margin-left: 10px" @click="reset_search">重置</a-button>
    </template>
    <!-- 操作的一系列东西 -->
    <template #operate>
      <a-button
        type="primary"
        style="margin-left: 10px"
        @click="showModal_add"
        v-checkpermission:foo.bar="'student_add'"
        ><template #icon><plus-outlined style="margin-right: 0" /></template
        >添加学生</a-button
      >
    </template>
  </x-search>
  <!-- 抽屉框--添加学生 -->
  <a-drawer v-model:open="open_add" title="新增权限" width="500">
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="学生姓名" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入学生姓名" />
      </a-form-item>
      <a-form-item label="性别" name="gender">
        <a-radio-group v-model:value="formState.gender">
          <a-radio value="男">男</a-radio>
          <a-radio value="女">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <!-- <a-form-item label="学生学号" name="student_id">
        <a-input
          v-model:value="formState.student_id"
          placeholder="请输入学生学号"
        />
      </a-form-item> -->
      <a-form-item label="学生班级" name="class_id">
        <a-select
          v-model:value="formState.class_id"
          placeholder="请选择学生班级"
        >
          <a-select-option
            v-for="(value, index) in all_classes"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="入学日期" name="enrol_date">
        <a-date-picker
          v-model:value="formState.enrol_date"
          show-time
          type="date"
        />
      </a-form-item>
      <a-form-item label="毕业日期" name="graduate_date">
        <a-date-picker
          v-model:value="formState.graduate_date"
          show-time
          type="date"
        />
      </a-form-item>
      <a-form-item label="学生学制" name="ed_sys">
        <a-select v-model:value="formState.ed_sys" placeholder="请选择学生学制">
          <a-select-option value="1"> 1年制 </a-select-option>
          <a-select-option value="2"> 2年制 </a-select-option>
          <a-select-option value="4"> 4年制 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="学生学历" name="ed_bkg">
        <a-select v-model:value="formState.ed_bkg" placeholder="请选择学生学历">
          <a-select-option value="初中"> 初中 </a-select-option>
          <a-select-option value="高中"> 高中 </a-select-option>
          <a-select-option value="专科"> 专科 </a-select-option>
          <a-select-option value="本科"> 本科 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="是否报考学历" name="call_ed_bkg">
        <a-radio-group v-model:value="formState.call_ed_bkg">
          <a-radio value="true">是</a-radio>
          <a-radio value="false">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="学生状态" name="state">
        <a-select
          v-model:value="formState.state"
          placeholder="请选择学生就读状态"
        >
          <a-select-option :value="0"> 在读 </a-select-option>
          <a-select-option :value="1"> 休学 </a-select-option>
          <a-select-option :value="2"> 退学 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="联系电话" name="phone">
        <a-input
          v-model:value="formState.phone"
          placeholder="请输入学生联系电话"
        />
      </a-form-item>
      <a-form-item label="紧急联系人" name="egy_person">
        <a-input
          v-model:value="formState.egy_person"
          placeholder="请输入学生紧急联系人"
        />
      </a-form-item>
      <a-form-item label="紧急联系人电话" name="egy_phone">
        <a-input
          v-model:value="formState.egy_phone"
          placeholder="请输入学生紧急联系人电话"
        />
      </a-form-item>
      <a-form-item label="籍贯" name="native_place">
        <a-input
          v-model:value="formState.native_place"
          placeholder="请输入学生籍贯"
        />
      </a-form-item>
      <a-form-item label="住址" name="address">
        <a-input
          v-model:value="formState.address"
          placeholder="请输入学生住址"
        />
      </a-form-item>
      <a-form-item label="电子邮箱" name="email">
        <a-input
          v-model:value="formState.email"
          placeholder="请输入学生电子邮箱"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" style="margin-left: 10px"
        >提交</a-button
      >
    </template>
  </a-drawer>
  <!-- 搜索下面的表格 -->
  <a-table
    :dataSource="dataSource"
    :columns="columns"
    :loading="loading"
    :pagination="{
      pageSize: state.pageSize,
      total: state.total,
      current: state.current,
      showSizeChanger: true, // 显示每页条数选择器
      pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数选项
      showTotal: (total) => `共 ${total} 条`, // 显示总条数
    }"
    @change="
      (pagination) => {
        console.log(pagination);
        state.pageSize = pagination.pageSize;
        state.total = pagination.total;
        state.current = pagination.current;
        student_list();
      }
    "
    :scroll="{ x: 1500, y: 600 }"
  >
    <!-- :columns="columns" :data-source="data" @resizeColumn="handleResizeColumn" -->
    <!-- 头部表头默认显示，不需要操作 -->
    <!-- <template #headerCell="{ column }"></template> -->
    <!-- 身体-表格中的列表 -->
    <!-- <template #bodyCell="{ column, record }"> -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'state'">
        <span>
          <!-- 学生的学习状态：0 在读；1 休学；2 退学 -->
          <a-tag color="green" v-if="record.state == 0">在读</a-tag>
          <a-tag color="orange" v-else-if="record.state == 1">休学</a-tag>
          <a-tag color="red" v-if="record.state == 2">退学</a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'ed_sys'">
        <a-tag
          :color="getEdSysColor(record.ed_sys)"
          :class="`ed-sys-${record.ed_sys}year`"
        >
          {{ record.ed_sys }}年制
        </a-tag>
      </template>
      <template v-else-if="column.key === 'ed_bkg'">
        <a-tag
          :color="educationMap[record.ed_bkg]?.color || '#d9d9d9'"
          :style="{
            fontWeight:
              educationMap[record.ed_bkg]?.level >= 3 ? 'bold' : 'normal',
            borderRadius: '4px',
          }"
        >
          {{ record.ed_bkg }}
        </a-tag>
      </template>
      <template v-else-if="column.key === 'enrol_date'">
        <span>{{ dayjs(record.enrol_date).format("YYYY-MM-DD") }}</span>
      </template>
      <template v-else-if="column.key === 'graduate_date'">
        <span>{{ dayjs(record.graduate_date).format("YYYY-MM-DD") }}</span>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <!-- 查看按钮 -->
          <a-tooltip title="查看" placement="top">
            <a-button
              type="text"
              size="small"
              @click="showModal_view(record.id)"
              v-checkpermission:foo.bar="'student_list'"
            >
              <template #icon>
                <EyeOutlined style="color: #1890ff" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 编辑按钮 -->
          <a-tooltip title="编辑" placement="top">
            <a-button
              type="text"
              size="small"
              @click="showModal_edit(record.id)"
              v-checkpermission:foo.bar="'student_edit'"
            >
              <template #icon>
                <EditOutlined style="color: #52c41a" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 状态切换按钮 -->
          <a-tooltip
            :title="record.state_del === 0 ? '禁用' : '启用'"
            placement="top"
          >
            <a-button
              type="text"
              size="small"
              :danger="record.state_del === 0"
              @click="
                record.state_del === 0
                  ? del_student_f(record.id)
                  : state_start(record.id)
              "
              v-checkpermission:foo.bar="'student_delete'"
            >
              <template #icon>
                <DeleteOutlined
                  :style="{
                    color: record.state_del === 0 ? '#ff4d4f' : '#52c41a',
                  }"
                />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 真删除按钮 -->
          <a-tooltip
            title="彻底删除"
            placement="top"
            v-if="record.state_del === 1"
          >
            <a-button
              type="text"
              size="small"
              danger
              @click="del_student_t(record.id)"
              v-checkpermission:foo.bar="'student_delete'"
            >
              <template #icon>
                <DeleteOutlined style="color: #cf1322" />
              </template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>
    </template>
  </a-table>
  <!-- 抽屉--编辑学生信息 -->
  <a-drawer v-model:open="open_edit" title="修改学生信息" width="500">
    <a-form
      ref="formRef_edit"
      :model="formState_edit"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="学生姓名" name="name">
        <a-input v-model:value="formState_edit.name" />
      </a-form-item>
      <a-form-item label="性别" name="gender">
        <a-radio-group v-model:value="formState_edit.gender">
          <a-radio value="男">男</a-radio>
          <a-radio value="女">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <!-- <a-form-item label="学生学号" name="student_id">
        <a-input v-model:value="formState_edit.student_id" />
      </a-form-item> -->
      <a-form-item label="学生班级" name="class_id">
        <a-select v-model:value="formState_edit.class_id">
          <a-select-option
            v-for="(value, index) in all_classes"
            :key="index"
            :value="value.id"
          >
            <span>{{ value.name }}</span>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="入学日期" name="enrol_date">
        <a-date-picker
          v-model:value="formState_edit.enrol_date"
          v-model:open="open_date1"
        >
          <template #renderExtraFooter>
            <a-button size="small" type="primary" @click="handleClose1"
              >取消</a-button
            >
          </template>
        </a-date-picker>
      </a-form-item>
      <a-form-item label="毕业日期" name="graduate_date">
        <a-date-picker
          v-model:value="formState_edit.graduate_date"
          v-model:open="open_date2"
        >
          <template #renderExtraFooter>
            <a-button size="small" type="primary" @click="handleClose2"
              >取消</a-button
            >
          </template>
        </a-date-picker>
      </a-form-item>

      <a-form-item label="学生学制" name="ed_sys">
        <a-select v-model:value="formState_edit.ed_sys">
          <a-select-option :value="1"> 1年制 </a-select-option>
          <a-select-option :value="2"> 2年制 </a-select-option>
          <a-select-option :value="4"> 4年制 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="学生学历" name="ed_bkg">
        <a-select v-model:value="formState_edit.ed_bkg">
          <a-select-option value="初中"> 初中 </a-select-option>
          <a-select-option value="高中"> 高中 </a-select-option>
          <a-select-option value="专科"> 专科 </a-select-option>
          <a-select-option value="本科"> 本科 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="是否报考学历" name="call_ed_bkg">
        <a-radio-group v-model:value="formState_edit.call_ed_bkg">
          <a-radio value="true">是</a-radio>
          <a-radio value="false">否</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="学生状态" name="state">
        <a-select v-model:value="formState_edit.state">
          <a-select-option :value="0"> 在读 </a-select-option>
          <a-select-option :value="1"> 休学 </a-select-option>
          <a-select-option :value="2"> 退学 </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="联系电话" name="phone">
        <a-input v-model:value="formState_edit.phone" />
      </a-form-item>
      <a-form-item label="紧急联系人" name="egy_person">
        <a-input v-model:value="formState_edit.egy_person" />
      </a-form-item>
      <a-form-item label="紧急联系人电话" name="egy_phone">
        <a-input v-model:value="formState_edit.egy_phone" />
      </a-form-item>
      <a-form-item label="籍贯" name="native_place">
        <a-input v-model:value="formState_edit.native_place" />
      </a-form-item>
      <a-form-item label="住址" name="address">
        <a-input v-model:value="formState_edit.address" />
      </a-form-item>
      <a-form-item label="电子邮箱" name="email">
        <a-input v-model:value="formState_edit.email" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleCancel_edit">取消</a-button>
      <a-button type="primary" @click="handleOk_edit" style="margin-left: 10px"
        >提交</a-button
      >
    </template>
  </a-drawer>
  <!-- 抽屉--查看学生信息 -->
  <a-drawer v-model:open="open_view" title="修改学生信息" width="500">
    <a-form ref="formRef_view" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="学生姓名" name="name">
        {{ formState_edit.name }}
      </a-form-item>
      <a-form-item label="性别" name="gender">
        {{ formState_edit.gender }}
      </a-form-item>
      <a-form-item label="学生学号" name="student_id">
        {{ formState_edit.student_id }}
      </a-form-item>
      <a-form-item label="学生班级" name="class_name">
        {{ formState_edit.class_name }}
      </a-form-item>
      <a-form-item label="入学日期" name="enrol_date">
        <a-date-picker v-model:value="formState_edit.enrol_date" disabled />
      </a-form-item>
      <a-form-item label="毕业日期" name="graduate_date">
        <a-date-picker v-model:value="formState_edit.graduate_date" disabled />
      </a-form-item>
      <a-form-item label="学生学制" name="ed_sys">
        <a-tag
          :color="getEdSysColor(formState_edit.ed_sys)"
          :class="`ed-sys-${formState_edit.ed_sys}year`"
        >
          {{ formState_edit.ed_sys }}年制
        </a-tag>
      </a-form-item>
      <a-form-item label="学生学历" name="ed_bkg">
        <a-tag
          :color="educationMap[formState_edit.ed_bkg]?.color || '#d9d9d9'"
          :style="{
            fontWeight:
              educationMap[formState_edit.ed_bkg]?.level >= 3
                ? 'bold'
                : 'normal',
            borderRadius: '4px',
          }"
        >
          {{ formState_edit.ed_bkg }}
        </a-tag>
      </a-form-item>
      <a-form-item label="是否报考学历" name="call_ed_bkg">
        <span v-if="formState_edit.call_ed_bkg == 'false'"> 否 </span>
        <span v-if="formState_edit.call_ed_bkg == 'true'"> 是 </span>
      </a-form-item>
      <a-form-item label="学生状态" name="state">
        <a-tag color="green" v-if="formState_edit.state == 0">在读</a-tag>
        <a-tag color="orange" v-if="formState_edit.state == 1">休学</a-tag>
        <a-tag color="red" v-if="formState_edit.state == 2">退学</a-tag>
      </a-form-item>
      <a-form-item label="联系电话" name="phone">
        {{ formState_edit.phone }}
      </a-form-item>
      <a-form-item label="紧急联系人" name="egy_person">
        {{ formState_edit.egy_person }}
      </a-form-item>
      <a-form-item label="紧急联系人电话" name="egy_phone">
        {{ formState_edit.egy_phone }}
      </a-form-item>
      <a-form-item label="籍贯" name="native_place">
        {{ formState_edit.native_place }}
      </a-form-item>
      <a-form-item label="住址" name="address">
        {{ formState_edit.address }}
      </a-form-item>
      <a-form-item label="电子邮箱" name="email">
        {{ formState_edit.email }}
      </a-form-item>
    </a-form>
  </a-drawer>
  <!-- </x-card> -->
</template>

<script lang="ts" setup>
import XSearch from "./XSearch.vue";
import { ref, reactive, toRaw, onMounted, createVNode } from "vue";
import http from "../routerutils/http";
import { message, Modal, Cascader } from "ant-design-vue";
// 对话提示
import {
  ExclamationCircleOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
// 表单验证
import type { Rule } from "ant-design-vue/es/form";
import type { UnwrapRef } from "vue";
import type { CascaderProps } from "ant-design-vue";
import { number } from "echarts";

import type { Dayjs } from "dayjs";
// 处理时间
import dayjs from "dayjs";
import { useStore } from "vuex";
const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

const value1 = ref<Dayjs>();
// 定义学历权重和颜色映射
const educationMap = {
  初中: { level: 1, color: "#f50" }, // 红色
  高中: { level: 2, color: "#2db7f5" }, // 蓝色
  专科: { level: 3, color: "#87d068" }, // 绿色
  本科: { level: 4, color: "#108ee9" }, // 深蓝色
};

// 学制颜色映射
const getEdSysColor = (edSys: any) => {
  const colorMap = {
    1: "gold", // 1年制用金色
    2: "lime", // 2年制用绿色
    4: "cyan", // 4年制用青色
  };
  return colorMap[edSys] || "gray";
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["10", "20", "50"],
});
// x-card组件中的属性值
const message_card = ref<string>("");
const height = ref<string>("850px");
// 日期的取消按钮
const open_date1 = ref<boolean>(false);
const handleClose1 = () => {
  open_date1.value = false;
};
const open_date2 = ref<boolean>(false);
const handleClose2 = () => {
  open_date2.value = false;
};
// 1. 搜索中的一系列数据以及操作
const student_name = ref<string>("");
const student_id = ref<string>("");
const ed_sys = ref<number>();
const class_id = ref<number>();
const program_id = ref<number>();
const student_state = ref<number>();
// 后端接口所有班级数据
const all_classes = ref<string[]>([]);
const all_class = async () => {
  try {
    const response = await http.get("/api/students/allclass");
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 后端接口所有专业数据
const all_programs = ref<string[]>([]);
const all_program = async () => {
  try {
    const response = await http.get("/api/students/allprogram");
    console.log(response.data.results);
    all_programs.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 重置搜索的按钮方法
const reset_search = () => {
  state.current = 1;
  student_name.value = "";
  student_id.value = "";
  ed_sys.value = null;
  class_id.value = null;
  program_id.value = null;
  student_state.value = null;
  student_list();
};
// 搜索按钮的方法
const but_search = () => {
  student_list();
};
// 2. 添加学生
// 添加学生的接口
const add_student = async () => {
  try {
    const response = await http.post("/api/students/add", {
      name: formState.name,
      gender: formState.gender,
      // student_id: formState.student_id,
      class_id: formState.class_id,
      enrol_date: dayjs(formState.enrol_date).format("YYYY-MM-DD HH:mm:ss"),
      graduate_date: dayjs(formState.graduate_date).format(
        "YYYY-MM-DD HH:mm:ss"
      ),
      ed_sys: formState.ed_sys,
      ed_bkg: formState.ed_bkg,
      call_ed_bkg: formState.call_ed_bkg,
      state: formState.state,
      phone: formState.phone,
      egy_person: formState.egy_person,
      egy_phone: formState.egy_phone,
      native_place: formState.native_place,
      address: formState.address,
      email: formState.email,
    });

    if (response.data.code === 0) {
      student_list();
      message.success(response.data.msg);
    } else {
      message.error(response.data.msg);
    }
    console.log(response);
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 谈话窗是否展示
const open_add = ref<boolean>(false);
const labelCol = { span: 7 };
const wrapperCol = { span: 15 };
const formRef = ref();
// 添加的按钮
const showModal_add = () => {
  open_add.value = true;
};
// 接口--修改和添加用一样的接口
interface FormState {
  name: string;
  gender: string;
  student_id: string;
  class_id: number;
  class_name?: string;
  enrol_date: Dayjs;
  graduate_date: Dayjs;
  ed_sys: number;
  ed_bkg: string;
  call_ed_bkg: string;
  state: number;
  phone: string;
  egy_person: string;
  egy_phone: string;
  native_place: string;
  address: string;
  email: string;
}
// 表单元素
const formState: UnwrapRef<FormState> = reactive({
  name: "",
  gender: "",
  student_id: "",
  class_id: null,
  enrol_date: "",
  graduate_date: "",
  ed_sys: null,
  ed_bkg: null,
  call_ed_bkg: 'true',
  state: null,
  phone: "",
  egy_person: "",
  egy_phone: "",
  native_place: "",
  address: "",
  email: "",
});
// 规则--修改和添加用一样的接口
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: "请输入权限名字", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  gender: [
    {
      required: true,
      message: "请选择性别",
      trigger: "change",
    },
  ],
  call_ed_bkg: [
    {
      required: true,
      message: "请选择性别",
      trigger: "change",
    },
  ],
  student_id: [
    { required: true, message: "请输入学号", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  class_id: [{ required: true, message: "请选择班级", trigger: "change" }],
  enrol_date: [
    { required: true, message: "请选择入学时间", trigger: "change" },
  ],
  graduate_date: [
    { required: true, message: "请选择毕业时间", trigger: "change" },
  ],
  ed_sys: [{ required: true, message: "请选择学制", trigger: "change" }],
  ed_bkg: [{ required: true, message: "请选择学历", trigger: "change" }],
  state: [{ required: true, message: "请选择学生状态", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "change" },
    {
      type: "string",
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  egy_person: [
    { required: true, message: "请输入紧急联系人姓名", trigger: "change" },
    { min: 2, message: "长度最少为2个字符串", trigger: "blur" },
  ],
  egy_phone: [
    { required: true, message: "请输入手机号", trigger: "change" },
    {
      type: "string",
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  native_place: [
    { required: true, message: "请输入学生的籍贯", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
  address: [
    { required: true, message: "请输入学生的住址", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "change" },
    {
      type: "string",
      pattern:
        /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
};
// 对话窗中的确定按钮
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log("values", formState, toRaw(formState));
      open_add.value = false;
      // 添加用户的接口
      add_student();
    })
    .catch((error: any) => {
      console.log("error", error);
    });
};
// 对话窗中的取消按钮
const handleCancel = () => {
  open_add.value = false;
};
// 3. 表格中的一系列操作及数据
const loading = ref(false); // 表格的加载
type Key = string | number;
// 表头
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    key: "id",
    width: 50,
    fixed: "left",
  },
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
    width: 100,
    fixed: "left",
  },
  {
    title: "学号",
    dataIndex: "student_id",
    key: "student_id",
    width: 150,
    fixed: "left",
  },
  {
    title: "班级",
    dataIndex: "class_name",
    key: "class_name",
    width: 100,
  },
  {
    title: "专业",
    dataIndex: "program_name",
    key: "program_name",
    width: 100,
  },
  {
    title: "学历",
    dataIndex: "ed_bkg",
    key: "ed_bkg",
    width: 90,
  },
  {
    title: "学制",
    dataIndex: "ed_sys",
    key: "ed_sys",
    width: 90,
  },
  {
    title: "入学时间",
    dataIndex: "enrol_date",
    key: "enrol_date",
    width: 130,
  },
  {
    title: "毕业时间",
    dataIndex: "graduate_date",
    key: "graduate_date",
    width: 130,
  },
  {
    title: "联系电话",
    dataIndex: "phone",
    key: "phone",
    width: 120,
  },
  {
    title: "紧急联系人",
    dataIndex: "egy_person",
    key: "egy_person",
    width: 120,
  },
  {
    title: "联系人电话",
    dataIndex: "egy_phone",
    key: "egy_phone",
    width: 120,
  },
  {
    title: "状态",
    dataIndex: "state",
    key: "state",
    width: 90,
  },
  {
    title: "操作",
    key: "action",
    width: 150,
    fixed: "right",
  },
];
// 表中数据
const dataSource = ref<string[]>([]);
// 勾选框的一系列操作
const state = reactive<{
  pageSize: number;
  total: number;
  current: number;
}>({
  pageSize: 10,
  total: 20,
  current: 1,
});
// 勾选时候的事件
// 请求后端列表接口
const student_list = async () => {
  try {
    loading.value = true; // 开始加载
    const response = await http.get("/api/students/list_search", {
      params: {
        name: student_name.value.trim(),
        student_id: student_id.value.trim(),
        ed_sys: ed_sys.value,
        class_id: class_id.value,
        program_id: program_id.value,
        state: student_state.value,
        page_size: state.pageSize,
        page: state.current,
      },
    });
    // console.log(response.data.data)
    const students = response.data.results.students;
    // 为每个用户对象添加一个唯一的 key 值，这里使用用户的 id 作为 key
    dataSource.value = students.map((student, index) => {
      return {
        ...student,
        key: student.id, // 确保每个对象都有一个唯一的 key 值
      };
    });
    state.total = response.data.results.total;
  } catch (error) {
    console.log("请求失败：：", error);
  } finally {
    loading.value = false; // 开始加载
  }
};
// 4. 修改用户一系列操作
// 修改用户--保存数据
const edit_id = ref<number>(); // 修改的id
// 表单元素
const formState_edit: UnwrapRef<FormState> = reactive({
  name: "",
  gender: "",
  student_id: "",
  class_id: null,
  // enrol_date: "", // 将字符串转换为moment对象,
  enrol_date: "", // 将字符串转换为moment对象,
  graduate_date: "", // 将字符串转换为moment对象,
  ed_sys: null,
  ed_bkg: "",
  call_ed_bkg: false,
  state: null,
  phone: "",
  egy_person: "",
  egy_phone: "",
  native_place: "",
  address: "",
  email: "",
  class_name: "",
});
// 修改-设置数据接口
const edit_save = async () => {
  try {
    const response = await http.post("/api/students/set", {
      id: edit_id.value,
      name: formState_edit.name,
      gender: formState_edit.gender,
      // student_id: formState_edit.student_id,
      class_id: formState_edit.class_id,
      enrol_date: dayjs(formState_edit.enrol_date).format(
        "YYYY-MM-DD HH:mm:ss"
      ),
      graduate_date: dayjs(formState_edit.graduate_date).format(
        "YYYY-MM-DD HH:mm:ss"
      ),
      ed_sys: formState_edit.ed_sys,
      ed_bkg: formState_edit.ed_bkg,
      call_ed_bkg: formState_edit.call_ed_bkg,
      state: formState_edit.state,
      phone: formState_edit.phone,
      egy_person: formState_edit.egy_person,
      egy_phone: formState_edit.egy_phone,
      native_place: formState_edit.native_place,
      address: formState_edit.address,
      email: formState_edit.email,
    });
    if (response.data.code === 0) {
      student_list();
      message.success(response.data.msg);
    } else {
      message.error(response.data.msg);
    }
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 弹窗的关闭与否
const open_edit = ref<boolean>(false);
const formRef_edit = ref();
// 打开谈话窗的按钮方法// 修改用户--获取数据
// 学生信息的获取--接口
const student_info = async (id: number) => {
  try {
    const response = await http.get("/api/students/get", {
      params: {
        id: id,
      },
    });
    console.log("被修改的学生信息:", response);
    formState_edit.name = response.data.results[0].name;
    formState_edit.gender = response.data.results[0].gender;
    formState_edit.student_id = response.data.results[0].student_id;
    formState_edit.class_id = response.data.results[0].class_id;
    // formState_edit.enrol_date = dayjs(response.data.results[0].enrol_date).format('YYYY-MM-DD');
    formState_edit.enrol_date = dayjs(response.data.results[0].enrol_date);
    // formState_edit.graduate_date = response.data.results[0].graduate_date;
    formState_edit.graduate_date = dayjs(
      response.data.results[0].graduate_date
    );

    formState_edit.ed_sys = response.data.results[0].ed_sys;
    formState_edit.ed_bkg = response.data.results[0].ed_bkg;
    formState_edit.call_ed_bkg = response.data.results[0].call_ed_bkg;
    formState_edit.state = response.data.results[0].state;
    formState_edit.phone = response.data.results[0].phone;
    formState_edit.egy_person = response.data.results[0].egy_person;
    formState_edit.egy_phone = response.data.results[0].egy_phone;
    formState_edit.native_place = response.data.results[0].native_place;
    formState_edit.address = response.data.results[0].address;
    formState_edit.email = response.data.results[0].email;
    formState_edit.class_name = response.data.results[0].class_name;
    edit_id.value = response.data.results[0].id;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 编辑按钮-方法
const showModal_edit = (id: number) => {
  // console.log(id)
  open_edit.value = true;
  student_info(id);
};
// 谈话框中点击确定的时候方法
const handleOk_edit = () => {
  formRef_edit.value
    .validate()
    .then(() => {
      console.log("values", formState_edit, toRaw(formState_edit));
      open_edit.value = false;
      // 修改用户--保存数据
      edit_save();
    })
    .catch((error) => {
      console.log("error", error);
    });
};
// 抽屉中取消的方法
const handleCancel_edit = () => {
  open_edit.value = false;
};
// 5. 查看学生信息
const open_view = ref<boolean>(false);
const formRef_view = ref<string>();
const showModal_view = (id: number) => {
  open_view.value = true;
  student_info(id);
};
// 6. 学生记录的软删除
const del_student_f = (id: number) => {
  // 删除用户的对话框
  Modal.confirm({
    title: "禁用用户",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要禁用此记录吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/students/delete_f", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        student_list();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
const state_start = async (id: number) => {
  try {
    const response = await http.get("/api/students/start", {
      params: {
        id: id,
      },
    });
    console.log(response);
    const msg = response.data.msg;
    message.success(msg);
    // 删除成功时候调用列表
    student_list();
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 7. 学生记录的软删除
const del_student_t = (id: number) => {
  // 删除用户的对话框
  Modal.confirm({
    title: "删除用户",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要删除此记录吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/students/delete_t", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        student_list();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
// 生命周期函数
onMounted(() => {
  all_class();
  all_program();
  student_list();
});

const range = (start: number, end: number) => {
  const result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
};

const disabledDate = (current: Dayjs) => {
  // Can not select days before today and today
  return current && current < dayjs().endOf("day");
};

const disabledDateTime = () => {
  return {
    disabledHours: () => range(0, 24).splice(4, 20),
    disabledMinutes: () => range(30, 60),
    disabledSeconds: () => [55, 56],
  };
};

const disabledRangeTime = (_: Dayjs, type: "start" | "end") => {
  if (type === "start") {
    return {
      disabledHours: () => range(0, 60).splice(4, 20),
      disabledMinutes: () => range(30, 60),
      disabledSeconds: () => [55, 56],
    };
  }
  return {
    disabledHours: () => range(0, 60).splice(20, 4),
    disabledMinutes: () => range(0, 31),
    disabledSeconds: () => [55, 56],
  };
};
</script>

<style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}

/* 自定义样式 */
.ed-sys-1year {
  font-weight: bold;
}
.ed-sys-2year {
  border-radius: 8px;
}
.ed-sys-4year {
  border-style: dashed;
}
</style>